""" 
按键 步进电机控制开关
key1 按1下正转, 再按反转
key2 按1下启动, 再按停止

危险提示:
    暂停程序之后, 确认电机可能过热损坏

"""

# 导入Pin模块
from machine import Pin
import time

# 按键引脚定义
key1 = Pin(14, Pin.IN, Pin.PULL_UP)  # 正转,反转
key2 = Pin(27, Pin.IN, Pin.PULL_UP)  # 启动,停止

# 步进电机引脚定义
motor_a = Pin(15, Pin.OUT, Pin.PULL_DOWN)
motor_b = Pin(2, Pin.OUT, Pin.PULL_DOWN)
motor_c = Pin(0, Pin.OUT, Pin.PULL_DOWN)
motor_d = Pin(4, Pin.OUT, Pin.PULL_DOWN)


def setup_motor_send_pulse(setup_value, fx_flag):
    # 停止转动
    if setup_value == 0:
        motor_a.value(1)
        motor_b.value(0)
        motor_c.value(0)
        motor_d.value(0)
        return

    setup = setup_value
    # fx: True 正转, False 反转
    if fx_flag == False:
        setup = 9 - setup_value

    print("setup:{} fx_flag:{}".format(setup, fx_flag))
    # return

    if setup == 1:
        motor_a.value(1)
        motor_b.value(0)
        motor_c.value(0)
        motor_d.value(0)
    elif setup == 2:
        motor_a.value(1)
        motor_b.value(1)
        motor_c.value(0)
        motor_d.value(0)
    elif setup == 3:
        motor_a.value(0)
        motor_b.value(1)
        motor_c.value(0)
        motor_d.value(0)
    elif setup == 4:
        motor_a.value(0)
        motor_b.value(1)
        motor_c.value(1)
        motor_d.value(0)
    elif setup == 5:
        motor_a.value(0)
        motor_b.value(0)
        motor_c.value(1)
        motor_d.value(0)
    elif setup == 6:
        motor_a.value(0)
        motor_b.value(0)
        motor_c.value(1)
        motor_d.value(1)
    elif setup == 7:
        motor_a.value(0)
        motor_b.value(0)
        motor_c.value(0)
        motor_d.value(1)
    elif setup == 8:
        motor_a.value(1)
        motor_b.value(0)
        motor_c.value(0)
        motor_d.value(1)


KEY1_Press = 0
KEY2_Press = 0
key_en=1

def key_scan():
    global key_en
    global KEY1_Press, KEY2_Press
    if key_en == 1 and (key1.value() == 0 or key2.value() == 0):
        time.sleep_ms(10)
        if key1.value() == 0:
            KEY1_Press = 1
        if key2.value() == 0:
            KEY2_Press = 1
        print("key1:{} key2:{}".format(KEY1_Press, KEY2_Press))
    elif key1.value() == 1 and key2.value() == 1:
        KEY1_Press = 0
        KEY2_Press = 0


if __name__ == "__main__":
    speed = 1
    setup = 1
    fx_flag = True  # 正/反转标志位
    start_stop_flag = True  # 启动/停止标志位
    while True:
        key_scan()
        if KEY1_Press == 1:
            fx_flag = not fx_flag
        if KEY2_Press == 1:
            start_stop_flag = not start_stop_flag

        if start_stop_flag == True:
            setup_motor_send_pulse(setup, fx_flag)
            time.sleep_ms(speed)
            setup += 1
            if setup > 8:
                setup = 1
        else:
            setup_motor_send_pulse(0, fx_flag)
